/**
 * Witontek.com.
 * Copyright (c) 2012-2018 All Rights Reserved.
 */
package test.encrypt.aes;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.sun.org.apache.xml.internal.security.utils.Base64;

/**
 * 
 * @author Long
 * @version $Id: Aes2.java, v 0.1 2018年7月3日 下午4:42:25  xiaolong.ma  Exp $
 */
public class Aes2 {

    /**
     * 
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        String content = "hello world";
        String password = "witon20189999999"; //此处使用AES-128-CBC加密模式，key需要为16位

        System.out.println("加密前：" + content);
        String encryptResult = encrypt(content, password);
        System.out.println("加密后：" + encryptResult);
        String decryptResult = decrypt(encryptResult, password);
        System.out.println("解密后：" + decryptResult);
    }

    //初始化向量，aes 16位
    private static final String IV = "abcdefghijk1mnop";

    //加密
    public static String encrypt(String content, String keyWord) throws Exception {
        try {
            SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
            byte[] encryptedData = cipher.doFinal(content.getBytes("UTF-8"));
            return Base64.encode(encryptedData);
        } catch (Exception e) {
            throw new Exception("加密失败");
        }
    }

    //解密
    public static String decrypt(String content, String keyWord) throws Exception {
        byte[] contentBytes = Base64.decode(content);
        try {
            SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
            byte[] result = cipher.doFinal(contentBytes);
            String s = new String(result);
            return s;
        } catch (Exception e) {
            throw new Exception("解密失败");
        }
    }
}
